<template>
  <div class="order-list">
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <div 
          v-for="order in orders" 
          :key="order.id"
          class="order-card"
          @click="goToOrderDetail(order.id)"
        >
          <div class="order-header">
            <div class="order-id">
              <van-icon name="orders-o" />
              <span>订单号：{{ order.orderNo }}</span>
            </div>
            <div 
              class="order-status-badge"
              :style="{ backgroundColor: getOrderStatusBgColor(order.status), color: getOrderStatusColor(order.status) }"
            >{{ order.statusText || getOrderStatusText(order.status) }}</div>
          </div>
          
          <div class="order-items">
            <div class="order-item">
              <div class="item-image">
                <img :src="order.image || 'https://img.yzcdn.cn/vant/cat.jpeg'" :alt="order.productName" />
              </div>
              <div class="item-info">
                <div class="item-name">{{ order.productName || '商品名称' }}</div>
                <div class="item-price-qty">
                  <span class="item-price">${{ formatNumber(order.price) }}USDT</span>
                  <span class="item-qty">x{{ order.specCount || 1 }}</span>
                </div>
                <div class="item-date" v-if="order.updatedAt">
                  <van-icon name="clock-o" />
                  <span>{{ order.updatedAt }}</span>
                </div>
              </div>
            </div>
          </div>
          
          <div class="order-footer">
            <div class="order-total">
              <span>共{{ order.specCount }}件</span>
              <span>合计：<span class="total-price">¥{{ formatNumber(order.payAmount) }} {{ order.currency }}</span></span>
            </div>
            
            <div class="order-actions">
              <!-- 动态渲染订单操作按钮 -->
              <template v-for="action in getOrderActions(order)" :key="action.name">
                <van-button 
                  size="small" 
                  :type="action.type"
                  :plain="action.type !== 'danger' && action.type !== 'primary'"
                  :class="`${action.name}-button`"
                  @click.stop="handleOrderAction(action.name, order)"
                >{{ action.text }}</van-button>
              </template>
            </div>
          </div>
        </div>
        
        <van-empty 
          v-if="orders.length === 0 && !loading" 
          description="暂无订单" 
        />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showDialog } from 'vant'
import { cancelOrder as apiCancelOrder, confirmReceived } from '@/api/order'
import { 
  getOrderStatusText, 
  getOrderStatusColor, 
  getOrderStatusBgColor,
  getOrderActions
} from '@/utils/orderStatus'
import { formatNumber } from '@/utils/utils'

const props = defineProps({
  orders: {
    type: Array,
    default: () => []
  },
  loading: {
    type: Boolean,
    default: false
  },
  finished: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['refresh', 'load'])

const router = useRouter()

// 列表状态
const refreshing = ref(false)
const loading = ref(props.loading)
const finished = ref(props.finished)

// 监听props变化
watch(() => props.loading, (newVal) => {
  loading.value = newVal
})

watch(() => props.finished, (newVal) => {
  finished.value = newVal
})


// 下拉刷新
const onRefresh = () => {
  emit('refresh')
  setTimeout(() => {
    refreshing.value = false
  }, 1000)
}

// 上拉加载
const onLoad = () => {
  emit('load')
}

// 跳转到订单详情
const goToOrderDetail = (orderId) => {
  router.push(`/order/${orderId}`)
}

// 取消订单
const cancelOrder = (order) => {
  showDialog({
    title: '取消订单',
    message: '确定要取消该订单吗？',
    showCancelButton: true
  }).then(() => {
    showToast({
      type: 'loading',
      message: '正在取消订单...',
      forbidClick: true,
      duration: 0
    })
    
    apiCancelOrder(order.id, '用户主动取消')
      .then(res => {
        if (res.code === 0) {
          showToast('订单已取消')
          // 立即刷新列表
          emit('refresh')
        } else {
          showToast(res.message || '取消订单失败')
        }
      })
      .catch(err => {
        console.error('取消订单出错:', err)
        showToast('取消订单出错，请稍后重试')
      })
  }).catch(() => {
    // 用户取消操作
  })
}

// 支付订单
const payOrder = (order) => {
  router.push(`/payment?orderId=${order.id}&amount=${order.totalAmount}`)
}

// 联系客服
const contactService = () => {
  router.push('/customer-service')
}

// 查看物流
const viewLogistics = (order) => {
  router.push(`/logistics?orderId=${order.id}`)
}

// 确认收货
const confirmReceipt = (order) => {
  showDialog({
    title: '确认收货',
    message: '确认已收到商品吗？确认后无法撤销。',
    showCancelButton: true
  }).then(() => {
    showToast({
      type: 'loading',
      message: '正在确认收货...',
      forbidClick: true,
      duration: 0
    })
    
    confirmReceived(order.id)
      .then(res => {
        if (res.code === 0) {
          showToast('确认收货成功')
          // 立即刷新列表
          emit('refresh')
        } else {
          showToast(res.message || '确认收货失败')
        }
      })
      .catch(err => {
        console.error('确认收货出错:', err)
        showToast('确认收货出错，请稍后重试')
      })
  }).catch(() => {
    // 用户取消操作
  })
}



// 申请售后
const applyRefund = (order) => {
  // 跳转到售后申请页面，并标记来源为订单列表
  router.push({
    path: '/refund',
    query: {
      orderId: order.id,
      from: 'list'
    }
  })
}

// 处理订单操作
const handleOrderAction = (actionName, order) => {
  switch (actionName) {
    case 'pay':
      payOrder(order)
      break
    case 'confirm':
      confirmReceipt(order)
      break
    case 'cancel':
      cancelOrder(order)
      break
    case 'refund':
      applyRefund(order)
      break
    case 'detail':
      goToOrderDetail(order.id)
      break
    case 'review':
      writeReview(order)
      break
    case 'buyAgain':
      buyAgain(order)
      break
    default:
      break
  }
}

// 评价订单
const writeReview = (order) => {
  router.push(`/review?orderId=${order.id}`)
}

// 再次购买
const buyAgain = () => {
  showToast('已添加到购物车')
  router.push('/cart')
}
</script>

<style scoped>
.order-list {
  padding: 12px;
}

.order-card {
  background-color: #ffffff;
  border-radius: 8px;
  margin-bottom: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #e2e8f0;
}

.order-id {
  display: flex;
  align-items: center;
  font-size: 13px;
  color: #64748b;
}

.order-id .van-icon {
  margin-right: 6px;
}

.order-status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.order-items {
  padding: 12px 16px;
}

.order-item {
  display: flex;
  padding: 8px 0;
}

.order-item:not(:last-child) {
  border-bottom: 1px solid #f1f5f9;
}

.item-image {
  width: 80px;
  height: 80px;
  margin-right: 12px;
  flex-shrink: 0;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.item-name {
  font-size: 15px;
  font-weight: 600;
  color: #1e293b;
  line-height: 1.4;
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.item-price-qty {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.item-price {
  font-size: 17px;
  font-weight: bold;
  color: #ef4444;
}

.item-qty {
  font-size: 12px;
  color: #64748b;
}

.item-date {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #94a3b8;
}

.item-date .van-icon {
  margin-right: 4px;
}

.order-footer {
  padding: 12px 16px;
  border-top: 1px solid #e2e8f0;
  background-color: #f8fafc;
}

.order-total {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 12px;
  font-size: 14px;
  color: #64748b;
  margin-bottom: 12px;
}

.total-price {
  font-weight: 500;
  color: #ef4444;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  background-color: #f8fafc;
}

.pay-button {
  background-color: #ef4444 !important;
  border-color: #ef4444 !important;
}

.confirm-button {
  background-color: #3b82f6 !important;
  border-color: #3b82f6 !important;
}

.cancel-button {
  border-color: #969799 !important;
  color: #969799 !important;
}

.detail-button {
  border-color: #c8c9cc !important;
  color: #1e293b !important;
}

.refund-button {
  color: #ff9800 !important;
  border-color: #ff9800 !important;
}

.review-button {
  background-color: #3b82f6 !important;
  border-color: #3b82f6 !important;
}

.buyAgain-button {
  border-color: #969799 !important;
  color: #969799 !important;
}
</style>
